"""
Comments
  Written by DanDye, 7/2008.
  Public Domain Software.

"""

#------------------------------
#--Dependencies----------------
#------------------------------
from minimal_exif_reader import MinimalExifReader
from GPX_parse import GPXParser
import glob
import os
import datetime
import time
from datetime import tzinfo, timedelta, datetime
import pytz
from pytz import timezone
from pytz import common_timezones
import xml.dom.minidom

#------------------------------
#--User Defined Stuff----------
#------------------------------
debug=1
pix_time_offset = timedelta(hours=4)

pix = glob.glob('C:\Documents and Settings\Dan\My Documents\My Pictures\Mellow Mushroom\*.jpg')
gpx = 'C:\Documents and Settings\Dan\My Documents\My Pictures\Mellow Mushroom\Track_20080810003504.gpx'

#gpx = 'C:\Documents and Settings\Dan\My Documents\My Pictures\Tamiami Trail\cut_Track_20080728020611.gpx'
#track = 'Track 013'
#kml_out = 'C:\Documents and Settings\Dan\My Documents\My Pictures\Tamiami Trail\kml.kml'

#pix = glob.glob('C:\Documents and Settings\Dan\My Documents\My Pictures\Street_View\*.jpg')
#gpx = 'C:\Documents and Settings\Dan\My Documents\My Pictures\Street_View\Track_20080809143303_v2.gpx'
#track = 'Track 007'


#------------------------------
#--Time and Timezone muck------
#------------------------------
#UTC_offset = -4  #this can be deprecated with use of pytz...NOT!
#UTC_offset = time(0,0,0,4,0,0) #4 hours
print "Time Zones in use:"
utc = pytz.timezone("UTC")
print utc

# DST isn't working for pytz so use naive time and adjust manually
#eastern = pytz.timezone('US/Eastern')
#print eastern


#------------------------------

print "Starting the program\n"


#------------------------------
print "GPX Stuff\n"
#------------------------------
#read the GPX file into an Object
g = GPXParser(gpx)
track_ns = g.tracks.keys()  #track keys are 
if debug: print "number of tracks in the GPX file is: ", str(len(track_ns))

#for debugging only. print the names of the tracks
if debug:
    for track_name_cnt in range(0,len(track_ns)):
        print "track_ns[track_name_cnt] is:", track_ns[track_name_cnt]
 
lats = []
lons = []
gpx_times = []
gpx_cnt = 0
for key_cnt in range(0,len(track_ns)):

    
    #get all of the t_stamps from the track
    t_stamps = g.tracks[track_ns[key_cnt]].keys()

    if debug:
        print "Now working on Track:", track_ns[key_cnt]
        print "First t_stamps for that track is:", t_stamps[0]
        print "The number of t_stamps for that track is:", str(len(t_stamps))

    #for each timestamp in the current track append it to the lat,lon,time arrays
    for i in range(0,len(t_stamps)):
        #print "Key: ", keys[i]
        t = time.strptime(t_stamps[i], "%Y-%m-%dT%H:%M:%SZ")
        #time, lat, lon indexes must match
        gpx_times.append([])
        lats.append([])
        lons.append([])

        gpx_times[gpx_cnt] = datetime(t[0],t[1],t[2],t[3],t[4],t[5], tzinfo=utc)
        lats[gpx_cnt] = g.tracks[track_ns[key_cnt]][t_stamps[i]]['lat']
        lons[gpx_cnt] = g.tracks[track_ns[key_cnt]][t_stamps[i]]['lon']
        gpx_cnt = gpx_cnt + 1
        #print gpx_times[i], " ", lats[i], " ", lons[i]
    print "done with that Track.  The i cnt is", i, " and the gpx_cnt is: ", gpx_cnt

#------------------------------
print "\nPix Stuff\n"
#------------------------------

pix_times = []

for i in range(0, len(pix)):
    pix_times.append([])
    fileName = pix[i]
    f = MinimalExifReader(fileName)
    t = time.strptime(f.dateTimeOriginal(), "%Y:%m:%d %H:%M:%S")
    pix_times[i] = datetime(t[0],t[1],t[2],t[3],t[4],t[5]) #removed tzinfo because DST is broken
    pix_times[i] = pix_times[i] + pix_time_offset #workaround for broken tzinfo

#------------------------------
print "\nDone with Pix Stuff\n"
#------------------------------    
    
#------------------------------
#--Write CSV Header------------
#------------------------------
f=open('C:/temp/out_file.txt', 'w')
f.write("Pix Time, GPS Time, Diff, Lat, Lon, File Name\n")

#------------------------------
#--Write KML Header------------
#------------------------------
kml_filename='C:/temp/out_file.kml'
kmlDoc = xml.dom.minidom.Document()
  
kmlElement = kmlDoc.createElementNS('http://earth.google.com/kml/2.2', 'kml')
kmlElement.setAttribute('xmlns','http://earth.google.com/kml/2.2')
kmlElement = kmlDoc.appendChild(kmlElement)

documentElement = kmlDoc.createElement('Document')
documentElement = kmlElement.appendChild(documentElement)
    
#--------------------------------------------------------------------
#--For each pix:
# ----Calculate which GPX time is closest to the Pix time------------
#--------------------------------------------------------------------
for pix_index in range(0,len(pix_times)):

    time_diff = [] #this array's subscripts will match gpx time,lat,lon

    for i in range(0, len(gpx_times)):

        time_diff.append([])
        
        #can't compare naive and aware tims.  Change the gpx_time to do the comparison.
        naive_gpx = datetime(gpx_times[i].year,gpx_times[i].month,gpx_times[i].day,gpx_times[i].hour,gpx_times[i].minute,gpx_times[i].second)

        #negative times cause problems so use absolute value instead
        if pix_times[pix_index] > naive_gpx:
            time_diff[i] =  pix_times[pix_index] - naive_gpx
        else:
            time_diff[i] = naive_gpx - pix_times[pix_index]

    #------------------------------
    #--Done with pix[pix_index]----
    #------------------------------            
    print "Done calculating time differences.  Write best fit to file."
    print "min time diff found: ", min(time_diff), "at array index: ", time_diff.index(min(time_diff))

#------------------------------
#--Write the CSV File----------
#------------------------------
    best_index = time_diff.index(min(time_diff))
    f.write(str((pix_times[pix_index])))
    f.write(",")
    f.write(str(gpx_times[best_index]))
    f.write(",")
    f.write(str(min(time_diff)))
    f.write(",")
    best_lat = lats[best_index]
    f.write(str(best_lat))
    f.write(",")
    best_lon = lons[best_index]
    f.write(str(best_lon))
    f.write(",")
    f.write(str(pix[pix_index]))
    f.write("\n")

#-------------------------------------
#--Add Placemark for each of the pix--
#-------------------------------------
    placemarkElement = kmlDoc.createElement('Placemark')
    placemarkElement = documentElement.appendChild(placemarkElement)
    
    nameElement = kmlDoc.createElement('name')
    strName = pix[pix_index]
    parts = strName.split('\\')
    print parts
    name = parts[len(parts)-1]
    #name = "test text"
    print name

    nameElement = kmlDoc.createElement('name')
    nameElement.appendChild(kmlDoc.createTextNode(name))
    nameElement = placemarkElement.appendChild(nameElement)

    snipElement = kmlDoc.createElement('snippet')
    snipElement.appendChild(kmlDoc.createTextNode("Snippet"))
    snipElement = placemarkElement.appendChild(snipElement)

    descriptionElement = kmlDoc.createElement('description')
    descriptionElement.appendChild(kmlDoc.createTextNode("<img src='"+pix[pix_index]+"' width='500' height='375'>"))
    descriptionElement = placemarkElement.appendChild(descriptionElement)

    pointElement = kmlDoc.createElement('Point')
    pointElement = placemarkElement.appendChild(pointElement)
    
    coorElement = kmlDoc.createElement('coordinates')
    coorElement.appendChild(kmlDoc.createTextNode(str(best_lon) + "," + str(best_lat)))
    coorElement = pointElement.appendChild(coorElement)

#------------------------------
#--Write the KML File----------
#------------------------------  
kmlFile = open(kml_filename, 'w')
kmlFile.write(kmlDoc.toprettyxml('  ', newl = '\n', encoding = 'utf-8'))

print "Fin!\n"

